package com.xiaoyu.client.ui.activity.forum;

import android.Manifest;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.baidu.location.Poi;
import com.bumptech.glide.Glide;
import com.techfansy.moreImageSelected.ImagePicker;
import com.techfansy.moreImageSelected.MoreImageMethod;
import com.techfansy.moreImageSelected.bean.ImageItem;
import com.xiaoyu.client.ClientConstants;
import com.xiaoyu.client.R;
import com.xiaoyu.client.adapter.seek.ForumAddAdapter;
import com.xiaoyu.client.network.NetworkManager;
import com.xiaoyu.client.ui.activity.NearbyActivity;
import com.xiaoyu.commonlib.BillionCardConstants;
import com.xiaoyu.commonlib.network.CommonHttpResponser;
import com.xiaoyu.commonlib.ui.base.BaseActivity;
import com.xiaoyu.commonlib.ui.widget.ContainsEmojiEditText;
import com.xiaoyu.commonlib.utils.AccessLocation;
import com.xiaoyu.commonlib.utils.MediaUtils;
import com.xiaoyu.commonlib.utils.StatusBarUtil;
import com.xiaoyu.commonlib.utils.ToastUtil;


import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayerStandard;


/**
 * 论坛（亿友圈）帖子添加页面
 */
public class ForumAddActivity extends BaseActivity implements View.OnClickListener, ForumAddAdapter.IDeleteImgListener {
    private static final int REQUEST_CODE_PICK = 1;
    private ImageView backBtn;//返回按钮
    private TextView sendBtn;//发布按钮

    @BindView(R.id.activity_forum_add_content_edit)
    ContainsEmojiEditText contentEdit;//内容编辑框
    @BindView(R.id.activity_forum_add_content_world_count)
    TextView worldCount;//编辑框当前输入文字数
    @BindView(R.id.activity_forum_add_location_layout)
    RelativeLayout mCityLayout;//定位项
    @BindView(R.id.activity_forum_add_location)
    TextView mLocation;//定位显示
    @BindView(R.id.activity_forum_add_upload_picture_btn)
    ImageView mUploadPictureBtn;//选择图片
    @BindView(R.id.activity_forum_add_upload_video_btn)
    ImageView mUploadVideoBtn;//选择视频

    @BindView(R.id.activity_forum_add_grid_view)
    GridView mGridView;


    private ForumAddAdapter mAdapter;
    private List<ImageItem> mList = new ArrayList<>();//选中的图片list
    private MoreImageMethod moreImageMethod;
    private ImagePicker imagePicker;
    private String videoPath = "";
    private Poi mPoi;
    private JCVideoPlayerStandard mPlayVideo;
    private String builderPath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forum_add);

        ButterKnife.bind(this);
        initView();
        moreImageMethod = new MoreImageMethod();
        imagePicker = ImagePicker.getInstance();
        imagePicker.clear();
    }

    private void initView() {
        backBtn = findViewById(R.id.activity_forum_add_title_back_btn);
        sendBtn = findViewById(R.id.activity_forum_add_title_send_btn);
        mPlayVideo = findViewById(R.id.player_list_video);

        mAdapter = new ForumAddAdapter(mList);
        mGridView.setAdapter(mAdapter);
        mAdapter.setIDeleteImg(this);

        mCityLayout.setOnClickListener(this);
        mUploadPictureBtn.setOnClickListener(this);
        mUploadVideoBtn.setOnClickListener(this);
        backBtn.setOnClickListener(this);
        sendBtn.setOnClickListener(this);
        contentEdit.addTextChangedListener(onContentWatcher);

    }

    @Override
    public void onClick(View v) {
        if (v == backBtn) {//返回
            onBackPressed();
        } else if (v == sendBtn) {//发布
            if (TextUtils.isEmpty(contentEdit.getText().toString())) {
                ToastUtil.showToast(this, "请填写内容");
                return;
            }
            if (mList.size() > 0) {
                showLoading();
                uploadImg();
            } else {
                showLoading();
                uploadOSSVideo(videoPath, videoPath.substring(videoPath.lastIndexOf("/") + 1));
            }
        } else if (v == mUploadPictureBtn) {//图片
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.CAMERA}, 1);
            moreImageMethod.setClick(this, mList, imagePicker);

        } else if (v == mUploadVideoBtn) {//视频
            choiceVideo();
        } else if (v == mCityLayout) {//定位
            Intent intent = new Intent(this, NearbyActivity.class);
            Bundle bundle = new Bundle();
            bundle.putParcelable(ClientConstants.Select_Location, mPoi);
            intent.putExtras(bundle);
            startActivityForResult(intent, 3);
        }
    }

    /**
     * 内容编辑框监听
     */
    private TextWatcher onContentWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            worldCount.setText(s.length() + "/50");
        }
    };

    /**
     * 从相册中选择视频
     */
    private void choiceVideo() {
        Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(i, REQUEST_CODE_PICK);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 3) {//位置选择
            if (data != null) {
                mPoi = data.getParcelableExtra(ClientConstants.Select_Location);
                mLocation.setText(mPoi.getName());
            }
        } else {
            //接收回调的图片
            mGridView.setVisibility(View.VISIBLE);
            moreImageMethod.onActivityResult(requestCode, resultCode, data, imagePicker, mList, ForumAddActivity.this);
            mAdapter.upDataList(mList);

            if (requestCode == REQUEST_CODE_PICK && resultCode == RESULT_OK && null != data) {
                Uri selectedVideo = data.getData();
                String[] filePathColumn = {MediaStore.Video.Media.DATA};
                Cursor cursor = getContentResolver().query(selectedVideo, filePathColumn, null, null, null);
                cursor.moveToFirst();
                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                videoPath = cursor.getString(columnIndex);

                mPlayVideo.setVisibility(View.VISIBLE);
                mGridView.setVisibility(View.GONE);
                boolean setUp = mPlayVideo.setUp(videoPath, JCVideoPlayer.SCREEN_LAYOUT_LIST, "");
                if (setUp) {
                    Glide.with(this).load(videoPath).into(mPlayVideo.thumbImageView);
                }

                cursor.close();

            }
        }
    }


    //发布接口
    private void issue(String fourming, String fourmvideo) {
        String videoImg = "";
        NetworkManager.issueForum(contentEdit.getText().toString(), fourming, fourmvideo, mLocation.getText().toString(), "", new CommonHttpResponser() {
            @Override
            public void onSuccess(String result) {
                Log.i("jx", "uploadOSSVideo:上传自己服务器成功===== " + System.currentTimeMillis());
                dissmissLoading();
                finish();
            }

            @Override
            public void onFailed(String errorCode, String errorDiscription) {
                dissmissLoading();
            }
        });
    }


    //上传图片值OSS
    private void uploadImg() {
        for (int i = 0; i < mList.size(); i++) {
            uploadOSSUrl(mList.get(i).getPaths(), mList.get(i).getName(), i);
        }
    }

    //上传图片
    private void uploadOSSUrl(String filePath, String objectKey, int position) {
        // 构造上传请求
        PutObjectRequest put = new PutObjectRequest(BillionCardConstants.BACKET_NAME, objectKey, filePath);
        OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(BillionCardConstants.ACCESS_KEY_ID, BillionCardConstants.ACCESS_KEY_SECRET);
        try {
            OSSClient oss = new OSSClient(this, BillionCardConstants.ENDPOINT, credentialProvider);
            PutObjectResult putResult = oss.putObject(put);
            if (position != mList.size() - 1) return;
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < mList.size(); i++) {
                builder.append("https://yikabangb.oss-cn-beijing.aliyuncs.com/" + mList.get(i).getName());
                builder.append(i != mList.size() - 1 ? "," : "");
            }
            issue(builder.toString(), "");//调取接口上传内容

        } catch (ClientException e) {
            // 本地异常如网络异常等
            e.printStackTrace();
        } catch (ServiceException e) {
            // 服务异常
        }
    }


    //上传视频
    private void uploadOSSVideo(String filePath, final String objectKey) {
        // 构造上传请求
        PutObjectRequest put = new PutObjectRequest(BillionCardConstants.BACKET_NAME, objectKey, filePath);

        // 异步上传时可以设置进度回调
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
            }
        });
        Log.i("jx", "uploadOSSVideo:准备上传七牛云===== " + System.currentTimeMillis());
        OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(BillionCardConstants.ACCESS_KEY_ID, BillionCardConstants.ACCESS_KEY_SECRET);
        OSSClient oss = new OSSClient(this, BillionCardConstants.ENDPOINT, credentialProvider);
        OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {

            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {

                StringBuilder builder = new StringBuilder();
                builder.append("https://yikabangb.oss-cn-beijing.aliyuncs.com/" + objectKey);
                Log.i("jx", "uploadOSSVideo:上传七牛云成功===== " + System.currentTimeMillis());
                issue("", builder.toString());//调取接口上传内容
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // 请求异常
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常
                }
            }
        });

        // task.cancel(); // 可以取消任务
        // task.waitUntilFinished(); // 可以等待任务完成

    }


    @Override
    public void deleteImg(int position) {
        mList.remove(position);
        moreImageMethod.images.remove(position);
        mAdapter.notifyDataSetChanged();
    }
}
